// eslint-disable-next-line
import { getUserMenus } from '@/api/system'
import { listToTree } from '@/utils/common'
import constantRouterComponents from './component-routers'
import path from 'path'

// 前端未找到页面路由（固定不用改）
const notFoundRouter = {
  path: '*',
  name: '404',
  hidden: true,
  component: () => import(/* webpackChunkName: "fail" */ '@/views/exception/404')
}
let rootRedirect = ''
let topRedirect = ''

/**
 * 动态生成菜单
 * @returns {Promise<Router>}
 */
export const generatorDynamicRouter = (params) => {
  return new Promise((resolve, reject) => {
    getUserMenus(params).then(async (res) => {
      const content = res.content || []
      if (!content || content.length < 2) {
        reject(new Error(''))
        return
      }
      const childrenNav = []
      //      后端数据, 根级树数组,  根级 PID
      listToTree(content, childrenNav, 0)
      const routers = await generator(childrenNav)
      routers[0].redirect = rootRedirect
      console.log(routers, rootRedirect)
      routers.push(notFoundRouter)
      resolve(routers)
    }).catch(err => {
      reject(err)
    })
  })
}

/**
 * 格式化树形结构数据 生成 vue-router 层级路由表
 *
 * @param routerMap
 * @param parent
 * @returns {*}
 */
export const generator = (routerMap, parent) => {
  return routerMap.map(item => {
    const { hideChildren, hiddenHeaderContent } = item.meta || {}
    const currentRouter = {
      // 如果路由设置了 path，则作为默认 path，否则 路由地址 动态拼接生成如 /dashboard/workplace
      path: item.path || `${parent && parent.path || ''}/${item.key}`,
      // 路由名称，建议唯一
      name: item.name + item.id,
      hidden: item.hidden || 0,
      icon: item.icon || 'bank',
      // 该路由对应页面的 组件 :方案1
      // component: constantRouterComponents[item.component || item.key],
      // 该路由对应页面的 组件 :方案2 (动态加载)
      component: constantRouterComponents[item.component] || constantRouterComponents['Error'],

      // meta: 组件类型, 组件, 页面标题
      meta: {
        id: item.id,
        isOutside: item.isOutside || 0,
        component: item.component,
        title: item.name || '菜单名称',
        hidden: item.hidden || 0,
        hiddenHeaderContent: hiddenHeaderContent,
        target: item.target,
        type: item.type
      }
    }
    // 是否设置了隐藏子菜单
    if (hideChildren) {
      currentRouter.hideChildrenInMenu = true
    }
    // 为了防止出现后端返回结果不规范，处理有可能出现拼接出两个 反斜杠
    if (!currentRouter.path.startsWith('http')) {
      currentRouter.path = currentRouter.path.replace('//', '/')
    }
    // 设置根节点的重定向地址
    if (item.parentId === 0 && item.path === '/') {
      topRedirect = item.path
    }
    if (topRedirect) { // 根结点的孩子，拼接根节点的重定向
      topRedirect = path.resolve(topRedirect, item.path)
    }
    item.redirect && (currentRouter.redirect = item.redirect)
    // 是否有子菜单，并递归处理
    if (item.children && item.children.length > 0) {
      currentRouter.redirect = path.resolve(currentRouter.redirect || item.path, item.children[0].path)
      currentRouter.children = generator(item.children, currentRouter)
    } else {
      topRedirect && (rootRedirect = topRedirect)
      topRedirect = ''
    }
    return currentRouter
  })
}
